<html lang="en-US">

<head>
    
<title>「连载四」TLS 证书认证 - 花落雨忧</title>

<meta property="og:title" content="「连载四」TLS 证书认证 - 花落雨忧">



    



    
    <meta property="description" content="在前面的章节里，我们介绍了 gRPC 的四种 API 使用方式。是不是很简单呢 😀
此时存在一个安全问题，先前的例子中 gRPC Client/Server 都是明文传输的，会不会有被窃听的风险呢？
从结论上来讲，是有的。在明文通讯的情况下，你的请求就是裸奔的，有可能被第三方恶意篡改或者伪造为“非法”的数据
[&amp;hellip;] 嗯，明文传输无误。这是有问题的，接下将改造我们的 gRPC，以便于解 &amp;hellip;">
    <meta property="og:description" content="在前面的章节里，我们介绍了 gRPC 的四种 API 使用方式。是不是很简单呢 😀
此时存在一个安全问题，先前的例子中 gRPC Client/Server 都是明文传输的，会不会有被窃听的风险呢？
从结论上来讲，是有的。在明文通讯的情况下，你的请求就是裸奔的，有可能被第三方恶意篡改或者伪造为“非法”的数据
[&amp;hellip;] 嗯，明文传输无误。这是有问题的，接下将改造我们的 gRPC，以便于解 &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.site/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.site/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.site/js/jquery.min.js"></script>




<link href="https://www.lican.site/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>
        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/go/grpc/2018-10-07-grpc-tls/">「连载四」TLS 证书认证</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2018/10/07</a>
                                            
                                            
                                            
                                            By 
                                            <a class="author" href="javascript:;">煎鱼</a></div>
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <h2 id="前言">前言</h2>
<p>在前面的章节里，我们介绍了 gRPC 的四种 API 使用方式。是不是很简单呢 😀</p>
<p>此时存在一个安全问题，先前的例子中 gRPC Client/Server 都是明文传输的，会不会有被窃听的风险呢？</p>
<p>从结论上来讲，是有的。在明文通讯的情况下，你的请求就是裸奔的，有可能被第三方恶意篡改或者伪造为“非法”的数据</p>
<h2 id="抓个包">抓个包</h2>
<p><img src="https://image.eddycjy.com/15e68df2ba9aa7cace3e26e35c79f200.jpg" alt="image"></p>
<p><img src="https://image.eddycjy.com/ebebd3ea7d306ad2fcd311f1d8b46cc0.jpg" alt="image"></p>
<p>嗯，明文传输无误。这是有问题的，接下将改造我们的 gRPC，以便于解决这个问题 😤</p>
<h2 id="证书生成">证书生成</h2>
<h3 id="私钥">私钥</h3>
<pre><code>openssl ecparam -genkey -name secp384r1 -out server.key
</code></pre><h3 id="自签公钥">自签公钥</h3>
<pre><code>openssl req -new -x509 -sha256 -key server.key -out server.pem -days 3650
</code></pre><h4 id="填写信息">填写信息</h4>
<pre><code>Country Name (2 letter code) []:
State or Province Name (full name) []:
Locality Name (eg, city) []:
Organization Name (eg, company) []:
Organizational Unit Name (eg, section) []:
Common Name (eg, fully qualified host name) []:go-grpc-example
Email Address []:
</code></pre><h3 id="生成完毕">生成完毕</h3>
<p>生成证书结束后，将证书相关文件放到 conf/ 下，目录结构：</p>
<pre><code>$ tree go-grpc-example
go-grpc-example
├── client
├── conf
│   ├── server.key
│   └── server.pem
├── proto
└── server
    ├── simple_server
    └── stream_server
</code></pre><p>由于本文偏向 gRPC，详解可参见 <a href="https://segmentfault.com/a/1190000013408485#articleHeader3">《制作证书》</a>。后续番外可能会展开细节描述 👌</p>
<h2 id="为什么之前不需要证书">为什么之前不需要证书</h2>
<p>在 simple_server 中，为什么“啥事都没干”就能在不需要证书的情况下运行呢？</p>
<h3 id="server">Server</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#a6e22e">grpc</span>.<span style="color:#a6e22e">NewServer</span>()
</code></pre></div><p>在服务端显然没有传入任何 DialOptions</p>
<h3 id="client">Client</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#a6e22e">conn</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">grpc</span>.<span style="color:#a6e22e">Dial</span>(<span style="color:#e6db74">&#34;:&#34;</span><span style="color:#f92672">+</span><span style="color:#a6e22e">PORT</span>, <span style="color:#a6e22e">grpc</span>.<span style="color:#a6e22e">WithInsecure</span>())
</code></pre></div><p>在客户端留意到 <code>grpc.WithInsecure()</code> 方法</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">WithInsecure</span>() <span style="color:#a6e22e">DialOption</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">newFuncDialOption</span>(<span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">o</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">dialOptions</span>) {
		<span style="color:#a6e22e">o</span>.<span style="color:#a6e22e">insecure</span> = <span style="color:#66d9ef">true</span>
	})
}
</code></pre></div><p>在方法内可以看到 <code>WithInsecure</code> 返回一个 <code>DialOption</code>，并且它最终会通过读取设置的值来禁用安全传输</p>
<p>那么它“最终”又是在哪里处理的呢，我们把视线移到 <code>grpc.Dial()</code> 方法内</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">DialContext</span>(<span style="color:#a6e22e">ctx</span> <span style="color:#a6e22e">context</span>.<span style="color:#a6e22e">Context</span>, <span style="color:#a6e22e">target</span> <span style="color:#66d9ef">string</span>, <span style="color:#a6e22e">opts</span> <span style="color:#f92672">...</span><span style="color:#a6e22e">DialOption</span>) (<span style="color:#a6e22e">conn</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">ClientConn</span>, <span style="color:#a6e22e">err</span> <span style="color:#66d9ef">error</span>) {
    <span style="color:#f92672">...</span>

    <span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">opt</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">opts</span> {
		<span style="color:#a6e22e">opt</span>.<span style="color:#a6e22e">apply</span>(<span style="color:#f92672">&amp;</span><span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">dopts</span>)
	}
    <span style="color:#f92672">...</span>

    <span style="color:#66d9ef">if</span> !<span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">dopts</span>.<span style="color:#a6e22e">insecure</span> {
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">dopts</span>.<span style="color:#a6e22e">copts</span>.<span style="color:#a6e22e">TransportCredentials</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span> {
			<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">errNoTransportSecurity</span>
		}
	} <span style="color:#66d9ef">else</span> {
		<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">dopts</span>.<span style="color:#a6e22e">copts</span>.<span style="color:#a6e22e">TransportCredentials</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
			<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">errCredentialsConflict</span>
		}
		<span style="color:#66d9ef">for</span> <span style="color:#a6e22e">_</span>, <span style="color:#a6e22e">cd</span> <span style="color:#f92672">:=</span> <span style="color:#66d9ef">range</span> <span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">dopts</span>.<span style="color:#a6e22e">copts</span>.<span style="color:#a6e22e">PerRPCCredentials</span> {
			<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">cd</span>.<span style="color:#a6e22e">RequireTransportSecurity</span>() {
				<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">errTransportCredentialsMissing</span>
			}
		}
	}
	<span style="color:#f92672">...</span>

	<span style="color:#a6e22e">creds</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">dopts</span>.<span style="color:#a6e22e">copts</span>.<span style="color:#a6e22e">TransportCredentials</span>
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">creds</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> <span style="color:#f92672">&amp;&amp;</span> <span style="color:#a6e22e">creds</span>.<span style="color:#a6e22e">Info</span>().<span style="color:#a6e22e">ServerName</span> <span style="color:#f92672">!=</span> <span style="color:#e6db74">&#34;&#34;</span> {
		<span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">authority</span> = <span style="color:#a6e22e">creds</span>.<span style="color:#a6e22e">Info</span>().<span style="color:#a6e22e">ServerName</span>
	} <span style="color:#66d9ef">else</span> <span style="color:#66d9ef">if</span> <span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">dopts</span>.<span style="color:#a6e22e">insecure</span> <span style="color:#f92672">&amp;&amp;</span> <span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">dopts</span>.<span style="color:#a6e22e">authority</span> <span style="color:#f92672">!=</span> <span style="color:#e6db74">&#34;&#34;</span> {
		<span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">authority</span> = <span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">dopts</span>.<span style="color:#a6e22e">authority</span>
	} <span style="color:#66d9ef">else</span> {
		<span style="color:#75715e">// Use endpoint from &#34;scheme://authority/endpoint&#34; as the default
</span><span style="color:#75715e"></span>		<span style="color:#75715e">// authority for ClientConn.
</span><span style="color:#75715e"></span>		<span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">authority</span> = <span style="color:#a6e22e">cc</span>.<span style="color:#a6e22e">parsedTarget</span>.<span style="color:#a6e22e">Endpoint</span>
	}
	<span style="color:#f92672">...</span>
}
</code></pre></div><h2 id="grpc">gRPC</h2>
<p>接下来我们将正式开始编码，在 gRPC Client/Server 上实现 TLS 证书认证的支持 🤔</p>
<h3 id="tls-server">TLS Server</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">main</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;context&#34;</span>
	<span style="color:#e6db74">&#34;log&#34;</span>
	<span style="color:#e6db74">&#34;net&#34;</span>

	<span style="color:#e6db74">&#34;google.golang.org/grpc&#34;</span>
	<span style="color:#e6db74">&#34;google.golang.org/grpc/credentials&#34;</span>

	<span style="color:#a6e22e">pb</span> <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-grpc-example/proto&#34;</span>
)

<span style="color:#f92672">...</span>

<span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> = <span style="color:#e6db74">&#34;9001&#34;</span>

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#a6e22e">c</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">credentials</span>.<span style="color:#a6e22e">NewServerTLSFromFile</span>(<span style="color:#e6db74">&#34;../../conf/server.pem&#34;</span>, <span style="color:#e6db74">&#34;../../conf/server.key&#34;</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;credentials.NewServerTLSFromFile err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">server</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">grpc</span>.<span style="color:#a6e22e">NewServer</span>(<span style="color:#a6e22e">grpc</span>.<span style="color:#a6e22e">Creds</span>(<span style="color:#a6e22e">c</span>))
	<span style="color:#a6e22e">pb</span>.<span style="color:#a6e22e">RegisterSearchServiceServer</span>(<span style="color:#a6e22e">server</span>, <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">SearchService</span>{})

	<span style="color:#a6e22e">lis</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">net</span>.<span style="color:#a6e22e">Listen</span>(<span style="color:#e6db74">&#34;tcp&#34;</span>, <span style="color:#e6db74">&#34;:&#34;</span><span style="color:#f92672">+</span><span style="color:#a6e22e">PORT</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;net.Listen err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">server</span>.<span style="color:#a6e22e">Serve</span>(<span style="color:#a6e22e">lis</span>)
}
</code></pre></div><ul>
<li>credentials.NewServerTLSFromFile：根据服务端输入的证书文件和密钥构造 TLS 凭证</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">NewServerTLSFromFile</span>(<span style="color:#a6e22e">certFile</span>, <span style="color:#a6e22e">keyFile</span> <span style="color:#66d9ef">string</span>) (<span style="color:#a6e22e">TransportCredentials</span>, <span style="color:#66d9ef">error</span>) {
	<span style="color:#a6e22e">cert</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">tls</span>.<span style="color:#a6e22e">LoadX509KeyPair</span>(<span style="color:#a6e22e">certFile</span>, <span style="color:#a6e22e">keyFile</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">err</span>
	}
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">NewTLS</span>(<span style="color:#f92672">&amp;</span><span style="color:#a6e22e">tls</span>.<span style="color:#a6e22e">Config</span>{<span style="color:#a6e22e">Certificates</span>: []<span style="color:#a6e22e">tls</span>.<span style="color:#a6e22e">Certificate</span>{<span style="color:#a6e22e">cert</span>}}), <span style="color:#66d9ef">nil</span>
}
</code></pre></div><ul>
<li>grpc.Creds()：返回一个 ServerOption，用于设置服务器连接的凭据。用于 <code>grpc.NewServer(opt ...ServerOption)</code> 为 gRPC Server 设置连接选项</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">Creds</span>(<span style="color:#a6e22e">c</span> <span style="color:#a6e22e">credentials</span>.<span style="color:#a6e22e">TransportCredentials</span>) <span style="color:#a6e22e">ServerOption</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">o</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">options</span>) {
		<span style="color:#a6e22e">o</span>.<span style="color:#a6e22e">creds</span> = <span style="color:#a6e22e">c</span>
	}
}
</code></pre></div><p>经过以上两个简单步骤，gRPC Server 就建立起需证书认证的服务啦 🤔</p>
<h3 id="tls-client">TLS Client</h3>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#f92672">package</span> <span style="color:#a6e22e">main</span>

<span style="color:#f92672">import</span> (
	<span style="color:#e6db74">&#34;context&#34;</span>
	<span style="color:#e6db74">&#34;log&#34;</span>

	<span style="color:#e6db74">&#34;google.golang.org/grpc&#34;</span>
	<span style="color:#e6db74">&#34;google.golang.org/grpc/credentials&#34;</span>

	<span style="color:#a6e22e">pb</span> <span style="color:#e6db74">&#34;github.com/EDDYCJY/go-grpc-example/proto&#34;</span>
)

<span style="color:#66d9ef">const</span> <span style="color:#a6e22e">PORT</span> = <span style="color:#e6db74">&#34;9001&#34;</span>

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#a6e22e">c</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">credentials</span>.<span style="color:#a6e22e">NewClientTLSFromFile</span>(<span style="color:#e6db74">&#34;../../conf/server.pem&#34;</span>, <span style="color:#e6db74">&#34;go-grpc-example&#34;</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;credentials.NewClientTLSFromFile err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">conn</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">grpc</span>.<span style="color:#a6e22e">Dial</span>(<span style="color:#e6db74">&#34;:&#34;</span><span style="color:#f92672">+</span><span style="color:#a6e22e">PORT</span>, <span style="color:#a6e22e">grpc</span>.<span style="color:#a6e22e">WithTransportCredentials</span>(<span style="color:#a6e22e">c</span>))
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;grpc.Dial err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}
	<span style="color:#66d9ef">defer</span> <span style="color:#a6e22e">conn</span>.<span style="color:#a6e22e">Close</span>()

	<span style="color:#a6e22e">client</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">pb</span>.<span style="color:#a6e22e">NewSearchServiceClient</span>(<span style="color:#a6e22e">conn</span>)
	<span style="color:#a6e22e">resp</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">client</span>.<span style="color:#a6e22e">Search</span>(<span style="color:#a6e22e">context</span>.<span style="color:#a6e22e">Background</span>(), <span style="color:#f92672">&amp;</span><span style="color:#a6e22e">pb</span>.<span style="color:#a6e22e">SearchRequest</span>{
		<span style="color:#a6e22e">Request</span>: <span style="color:#e6db74">&#34;gRPC&#34;</span>,
	})
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Fatalf</span>(<span style="color:#e6db74">&#34;client.Search err: %v&#34;</span>, <span style="color:#a6e22e">err</span>)
	}

	<span style="color:#a6e22e">log</span>.<span style="color:#a6e22e">Printf</span>(<span style="color:#e6db74">&#34;resp: %s&#34;</span>, <span style="color:#a6e22e">resp</span>.<span style="color:#a6e22e">GetResponse</span>())
}
</code></pre></div><ul>
<li>credentials.NewClientTLSFromFile()：根据客户端输入的证书文件和密钥构造 TLS 凭证。serverNameOverride 为服务名称</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">NewClientTLSFromFile</span>(<span style="color:#a6e22e">certFile</span>, <span style="color:#a6e22e">serverNameOverride</span> <span style="color:#66d9ef">string</span>) (<span style="color:#a6e22e">TransportCredentials</span>, <span style="color:#66d9ef">error</span>) {
	<span style="color:#a6e22e">b</span>, <span style="color:#a6e22e">err</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">ioutil</span>.<span style="color:#a6e22e">ReadFile</span>(<span style="color:#a6e22e">certFile</span>)
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">err</span> <span style="color:#f92672">!=</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">err</span>
	}
	<span style="color:#a6e22e">cp</span> <span style="color:#f92672">:=</span> <span style="color:#a6e22e">x509</span>.<span style="color:#a6e22e">NewCertPool</span>()
	<span style="color:#66d9ef">if</span> !<span style="color:#a6e22e">cp</span>.<span style="color:#a6e22e">AppendCertsFromPEM</span>(<span style="color:#a6e22e">b</span>) {
		<span style="color:#66d9ef">return</span> <span style="color:#66d9ef">nil</span>, <span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Errorf</span>(<span style="color:#e6db74">&#34;credentials: failed to append certificates&#34;</span>)
	}
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">NewTLS</span>(<span style="color:#f92672">&amp;</span><span style="color:#a6e22e">tls</span>.<span style="color:#a6e22e">Config</span>{<span style="color:#a6e22e">ServerName</span>: <span style="color:#a6e22e">serverNameOverride</span>, <span style="color:#a6e22e">RootCAs</span>: <span style="color:#a6e22e">cp</span>}), <span style="color:#66d9ef">nil</span>
}
</code></pre></div><ul>
<li>grpc.WithTransportCredentials()：返回一个配置连接的 DialOption 选项。用于 <code>grpc.Dial(target string, opts ...DialOption)</code> 设置连接选项</li>
</ul>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-go" data-lang="go"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">WithTransportCredentials</span>(<span style="color:#a6e22e">creds</span> <span style="color:#a6e22e">credentials</span>.<span style="color:#a6e22e">TransportCredentials</span>) <span style="color:#a6e22e">DialOption</span> {
	<span style="color:#66d9ef">return</span> <span style="color:#a6e22e">newFuncDialOption</span>(<span style="color:#66d9ef">func</span>(<span style="color:#a6e22e">o</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">dialOptions</span>) {
		<span style="color:#a6e22e">o</span>.<span style="color:#a6e22e">copts</span>.<span style="color:#a6e22e">TransportCredentials</span> = <span style="color:#a6e22e">creds</span>
	})
}
</code></pre></div><h2 id="验证">验证</h2>
<h3 id="请求">请求</h3>
<p>重新启动 server.go 和执行 client.go，得到响应结果</p>
<pre><code>$ go run client.go
2018/09/30 20:00:21 resp: gRPC Server
</code></pre><h3 id="抓个包-1">抓个包</h3>
<p><img src="https://image.eddycjy.com/c8ad6edf1f7d084883b847b3eee29dd2.jpg" alt="image"></p>
<p>成功。</p>
<h2 id="总结">总结</h2>
<p>在本章节我们实现了 gRPC TLS Client/Servert，你以为大功告成了吗？我不 😤</p>
<h2 id="问题">问题</h2>
<p>你仔细再看看，Client 是基于 Server 端的证书和服务名称来建立请求的。这样的话，你就需要将 Server 的证书通过各种手段给到 Client 端，否则是无法完成这项任务的</p>
<p>问题也就来了，你无法保证你的“各种手段”是安全的，毕竟现在的网络环境是很危险的，万一被&hellip;</p>
<p>我们将在下一章节解决这个问题，保证其可靠性 🙂</p>
<h2 id="参考">参考</h2>
<h3 id="本系列示例代码">本系列示例代码</h3>
<ul>
<li><a href="https://github.com/EDDYCJY/go-grpc-example">go-grpc-example</a></li>
</ul>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-09-24-stream-client-server/">「连载三」gRPC Streaming, Client and Server</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-09-23-client-and-server/">「连载二」gRPC Client and Server</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/grpc/2018-09-22-install/">「连载一」gRPC及相关介绍</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/pkg/2018-09-28-log/">log 标准库</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/tools/2018-09-15-go-tool-pprof/">Go 大杀器之性能剖析 PProf</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            <li>
                                                <a href="/tags/grpc" title="View all posts tagged match">grpc</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.site/posts/go/pkg/2018-09-28-log/"
                                                    rel="prev">log 标准库</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.site/posts/go/grpc/2018-10-08-ca-tls/">「连载五」基于 CA 的 TLS 证书认证</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.site/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.vip All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>